import React, {useState} from "react";
import {useLocation, useNavigate} from "react-router-dom";
import type { MenuProps } from 'antd';
import {Menu} from "antd";
import {DesktopOutlined, FileOutlined, PieChartOutlined, TeamOutlined, UserOutlined} from "@ant-design/icons";
type MenuItem = Required<MenuProps>['items'][number];

const items: MenuItem[] = [
    {
        label: '栏目1',
        key: '/page1',
        icon: <DesktopOutlined />
    },
    {
        label: '栏目2',
        key: '/page2',
        icon: <FileOutlined />
    },
    {
        label: '栏目3',
        key: '/page3',
        icon: <PieChartOutlined />,
        children: [
            {
                label: '子栏目1',
                key: '/page4',
                icon: <TeamOutlined />
            },
            {
                label: '子栏目2',
                key: '/page5',
                icon: <UserOutlined />
            },
        ]
    },
];
const MainMenu: React.FC = () => {
    let initOpenKeys:string = ''
    const navigateTo = useNavigate()
    const currentRouter = useLocation()
    function findKey(obj: {key: string}) {
        return obj.key === currentRouter.pathname
    }
    for (let i = 0; i < items.length; i++) {
        if(items[i]!['children'] && items[i]!['children'].length > 0 && items[i]!['children'].find(findKey)) {
            initOpenKeys = items[i]!['key'] as string;
            break
        }
    }
    const [openKeys, setOpenKeys] = useState([initOpenKeys])
    const menuChangeHandler = (e: { key: string }) => {
        navigateTo(e.key)
    }
    const handleOpenChange = (keys: string[]) => {
        setOpenKeys([keys[keys.length - 1]])
    }
    return (
        <Menu
            theme="dark"
            defaultSelectedKeys={[currentRouter.pathname]}
            mode="inline"
            items={items}
            openKeys={openKeys}
            onClick={menuChangeHandler}
            onOpenChange={handleOpenChange}
        />
    );
};
export default MainMenu